package com.srt.util.service;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ReflectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

public class CommonService<M extends CommonMapper<T>, T> extends ServiceImpl<M, T> {

    public int deleteByIdWithFill(Long id) {
        QueryWrapper<T> wrapper = (QueryWrapper) Wrappers.query().eq("id", id);
        return this.batchDeleteWithFill(wrapper);
    }

    public int batchDeleteWithFill(Wrapper<T> wrapper) {
        T param = ReflectUtil.newInstance(this.currentModelClass(), new Object[0]);
        return ((CommonMapper)this.getBaseMapper()).batchDeleteWithFill(param, wrapper);
    }

    protected boolean exists(String name, SFunction<T, ?> sFunction) {
        Object obj = super.getOne(((LambdaQueryWrapper)(new QueryWrapper()).lambda().eq(sFunction, name)).last(true, "LIMIT 1"));
        return obj != null;
    }

    protected boolean exists(List<ExistsCondition<T>> conditions) {
        if (CollectionUtils.isEmpty(conditions)) {
            return false;
        } else {
            LambdaQueryWrapper<T> queryWrapper = this.getQueryWrapper(conditions);
            Object obj = super.getOne(queryWrapper.last(true, "LIMIT 1"));
            return obj != null;
        }
    }

    private LambdaQueryWrapper<T> getQueryWrapper(List<ExistsCondition<T>> conditions) {
        LambdaQueryWrapper<T> queryWrapper = (new QueryWrapper()).lambda();
        Iterator var3 = conditions.iterator();

        while(var3.hasNext()) {
            ExistsCondition condition = (ExistsCondition)var3.next();
            queryWrapper.eq(condition.getSFunction(), condition.getValue());
        }

        return queryWrapper;
    }

    public List<T> listByInIds(Collection<? extends Serializable> idList) {
        return (List)(CollectionUtils.isNotEmpty(idList) ? this.listByIds(idList) : ListUtil.list(false));
    }
}

